package top.lyc829.iot_server.controller;

import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.stereotype.Service;
import top.lyc829.iot_server.service.FingerService;
import top.lyc829.iot_server.service.NfcService;
import top.lyc829.iot_server.utils.MqttUtil;
import top.lyc829.iot_server.utils.UserContainer;

import javax.annotation.Resource;
import java.util.Date;


@Service
public class IotController {

    private final static String OPENWITHNFC = "/server/open_nfc";
    private final static String OPENWITHFINGER = "/server/open_finger";
    private final static String ADDFINGERSUCCESS = "/server/add_finger_success";
    private final static String ADDCARDSUCCESS = "/server/add_card_success";
    private final static String CLOSEDOOR = "/server/close_door";
    private final static String OPENDOOR = "/server/open_door";
    private volatile Date oldDate;

    @Resource
    private NfcService nfcService;
    @Resource
    private FingerService fingerService;
    @Resource
    private UserContainer userContainer;

    private MqttUtil mqttUtil;

    private volatile int gateStatus; //门的状态 0：关 1：开


    public IotController(){
        registerHandle();
        gateStatus = 0;
        sendGateStatus();
        oldDate = new Date();
    }

    /*
     * 发送门的状态
     */
    private void sendGateStatus(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    mqttUtil.publish("/app/door_status",gateStatus+"");
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    /*
     * 处理接收到的mqtt消息
     */
    public void registerHandle(){
        mqttUtil = MqttUtil.build();

        mqttUtil.subscribe(OPENWITHNFC, new MqttUtil.Callable() {
            @Override
            public void callback(MqttMessage mqttMessage) {
                Date newDate = new Date();
                if (newDate.getTime() - oldDate.getTime() > 1000){
                    nfcHandle(mqttMessage.toString());
                }
                oldDate = newDate;
            }
        });

        mqttUtil.subscribe(OPENWITHFINGER, new MqttUtil.Callable() {
            @Override
            public void callback(MqttMessage mqttMessage) {
                // 间隔3秒才响应一次
                Date newDate = new Date();
                if (newDate.getTime() - oldDate.getTime() > 3000){
                    fingerHandle(mqttMessage.toString());
                }
                oldDate = newDate;
            }
        });

        mqttUtil.subscribe(ADDCARDSUCCESS, new MqttUtil.Callable() {
            @Override
            public void callback(MqttMessage mqttMessage) {
                addCardHandle(mqttMessage.toString());
            }
        });

        mqttUtil.subscribe(ADDFINGERSUCCESS, new MqttUtil.Callable() {
            @Override
            public void callback(MqttMessage mqttMessage) {
                addFingerSuccess(mqttMessage.toString());
            }
        });

        mqttUtil.subscribe(CLOSEDOOR, new MqttUtil.Callable() {
            @Override
            public void callback(MqttMessage mqttMessage) {
                if (gateStatus == 0) return;
                Date newDate = new Date();
                if (newDate.getTime() - oldDate.getTime() > 1000){
                    closeDoor();
                }
                oldDate = newDate;
            }
        });

        mqttUtil.subscribe(OPENDOOR, new MqttUtil.Callable() {
            @Override
            public void callback(MqttMessage mqttMessage) {
                if (gateStatus == 1) return;
                Date newDate = new Date();
                if (newDate.getTime() - oldDate.getTime() > 1000){
                    openDoor();
                }
                oldDate = newDate;
            }
        });

    }


    /*
     * nfc 开门
     */
    public void nfcHandle(String content){
        if (gateStatus == 1) return;
        String name = null;
        if ((name = nfcService.open(content)) != null){
            // 开门成功
            gateStatus = 1;
            mqttUtil.publish("/client/open_gate","");
            mqttUtil.publish("/client/welcome",name);
        }else {
            mqttUtil.publish("/client/open_error","");
        }
    }


    /*
     * 指纹开门
     */
    public void fingerHandle(String content){
        if (gateStatus == 1) return;
        String name = null;
        if ((name = fingerService.open(content)) != null){
            //开门成功
            gateStatus = 1;
            mqttUtil.publish("/client/open_gate","");
            mqttUtil.publish("/client/welcome",name);
        }else {
            mqttUtil.publish("/client/open_error","");
        }
    }

    /*
     * 监听关门
     */
    public void closeDoor(){
        mqttUtil.publish("/client/close_gate","");
        gateStatus = 0;
    }

    /*
     * 监听开门
     */
    public void openDoor(){
        mqttUtil.publish("/client/open_gate","");
        mqttUtil.publish("/client/welcome",userContainer.getName());
        gateStatus = 1;
    }

    /*
     * 添加卡成功
     */
    public void addCardHandle(String content){
        // 保存记录
        userContainer.saveNfcId(content);
        mqttUtil.publish("/client/store_card","");
    }

    /*
     * 添加指纹成功
     */
    public void addFingerSuccess(String content){
        Integer fingerId = Integer.parseInt(content);
        userContainer.saveFingerId(fingerId);
        mqttUtil.publish("/client/store_finger","");
    }

}
